import { FolderOutlined } from "@ant-design/icons";
import type { MenuProps } from "antd";
import { Dropdown, Modal } from "antd";
import { MenuButton } from "./MenuButton.tsx";
import FileSaver from "file-saver";
import { isShowChild } from "@meta2d/core";
import JSZip from "jszip";
import localforage from "localforage";
import { meta2dOptions } from "@/config";
import { useState } from "react";

interface FileActions {
  onSave?: () => Promise<any>;
  onNewFile?: () => void;
}

const items: MenuProps["items"] = [
  {
    key: "newFile",
    label: "新建文件",
  },
  {
    key: "openFile",
    label: "打开文件",
  },
  {
    type: "divider",
  },
  {
    key: "save",
    label: "保存",
  },
  {
    key: "downloadJson",
    label: "下载JSON文件",
  },
  {
    key: "downloadZip",
    label: "下载ZIP打包文件",
  },
  {
    type: "divider",
  },
  {
    key: "downloadPng",
    label: "下载为PNG",
  },
  {
    key: "downloadSvg",
    label: "下载为SVG",
  },
];

const newFile = async () => {
  await localforage.removeItem("meta2d");
  await localforage.removeItem("meta2dOptions");
  window.meta2d.open({ name: "新建项目", pens: [] } as any);
  window.meta2d.setOptions(meta2dOptions);
  window.meta2d.render(true);
};

function readFile(file: Blob) {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result as string);
    };
    reader.onerror = reject;
    reader.readAsText(file);
  });
}

const openFile = () => {
  // 1. 显示选择文件对话框
  const input = document.createElement("input");
  input.type = "file";
  input.onchange = async (event) => {
    const elem = event.target as HTMLInputElement;
    if (elem.files && elem.files[0]) {
      // 2. 读取文件字符串内容
      const text = await readFile(elem.files[0]);
      try {
        // 3. 打开文件内容
        window.meta2d.open(JSON.parse(text));

        // 可选：缩放到窗口大小展示
        window.meta2d.fitView();
      } catch (e) {
        console.log(e);
      }
    }
  };
  input.click();
};
const downloadJson = () => {
  const data: any = window.meta2d.data();
  FileSaver.saveAs(
    new Blob([JSON.stringify(data)], {
      type: "text/plain;charset=utf-8",
    }),
    `${data.name || "tl.meta2d_" + Date.now()}.json`,
  );
};

const downloadPng = () => {
  let name = (window.meta2d.store.data as any).name;
  if (name) {
    name += ".png";
  }
  window.meta2d.downloadPng(name);
};
const downloadSvg = () => {
  if (!window.C2S) {
    return;
  }

  const rect: any = window.meta2d.getRect();
  rect.x -= 10;
  rect.y -= 10;
  const ctx = new window.C2S(rect.width + 20, rect.height + 20);
  ctx.textBaseline = "middle";
  for (const pen of window.meta2d.store.data.pens) {
    if (pen.visible == false || !isShowChild(pen, window.meta2d.store)) {
      continue;
    }
    window.meta2d.renderPenRaw(ctx, pen, rect);
  }

  let mySerializedSVG = ctx.getSerializedSvg();
  if (window.meta2d.store.data.background) {
    mySerializedSVG = mySerializedSVG.replace("{{bk}}", "");
    mySerializedSVG = mySerializedSVG.replace(
      "{{bkRect}}",
      `<rect x="0" y="0" width="100%" height="100%" fill="${window.meta2d.store.data.background}"></rect>`,
    );
  } else {
    mySerializedSVG = mySerializedSVG.replace("{{bk}}", "");
    mySerializedSVG = mySerializedSVG.replace("{{bkRect}}", "");
  }

  mySerializedSVG = mySerializedSVG.replace(/--le5le--/g, "&#x");

  const urlObject: any = (window as any).URL || window;
  const export_blob = new Blob([mySerializedSVG]);
  const url = urlObject.createObjectURL(export_blob);

  const a = document.createElement("a");
  a.setAttribute(
    "download",
    `${(window.meta2d.store.data as any).name || "le5le.meta2d"}.svg`,
  );
  a.setAttribute("href", url);
  const evt = document.createEvent("MouseEvents");
  evt.initEvent("click", true, true);
  a.dispatchEvent(evt);
};

const downloadZip = () => {
  const data: any = window.meta2d.data();
  const zip = new JSZip();
  let nowData = Date.now();
  zip.file(`${data.name || `tl.meta2d_${nowData}`}.json`, JSON.stringify(data));
  zip.generateAsync({ type: "blob" }).then(function (content) {
    // 下载Zip文件
    FileSaver.saveAs(content, `${data.name || `tl.meta2d_${nowData}`}.zip`);
  });
};

export const FileDropDown = (props: FileActions) => {
  const [open, setOpen] = useState(false);
  const onClick: MenuProps["onClick"] = ({ key }) => {
    switch (key) {
      case "newFile":
        setOpen(true);
        break;
      case "openFile":
        openFile();
        break;
      case "downloadPng":
        downloadPng();
        break;
      case "downloadJson":
        downloadJson();
        break;
      case "downloadSvg":
        downloadSvg();
        break;
      case "save":
        props.onSave && props.onSave();
        break;
      case "downloadZip":
        downloadZip();
        break;
      default:
        break;
    }
  };
  return (
    <>
      <Dropdown arrow menu={{ items, onClick }}>
        <a onClick={(e) => e.preventDefault()}>
          <MenuButton
            arrow
            children={<FolderOutlined />}
            title="文件"
          ></MenuButton>
        </a>
      </Dropdown>
      <Modal
        title="提示"
        open={open}
        centered
        okText={"确定"}
        cancelText={"取消"}
        onOk={() => {
          newFile().then(() => {
            props.onNewFile && props.onNewFile();
            setOpen(false);
          });
        }}
        onCancel={() => setOpen(false)}
      >
        <p>系统可能不会保存您所做的更改，是否继续？</p>
      </Modal>
    </>
  );
};
